import { http } from '@/utils/luch-request/index.js'
import md5js from "@/config/md5.js";
import {apiObj} from "@/utils/api-obj.js";
import {btoa,atod} from "@/utils/fileupload/base64_func.js";
var uploadImgList = []; //h5图片转jpg格式之后存放的路径
var uploadImgListH5Qiniu = []; //h5上传七牛之后的路劲
var uploadVideoList = []; //上传视频存放的路径
var uploadVideoListQiniu = []; //上传七牛之后视频存放的路径
var uploadFileList = []; //上传视频存放的路径
var uploadFileListQiniu = []; //上传七牛之后文件存放的路径
var uploadImageAllowSize = 0; //允许上传图片的最大大小
var cacheKey = 'qiniuUploadConfig'; ////七牛缓存key
export default {
	//去除文件左边的/符号
	leftTrim(str) {  
	  if (str.charAt(0) == '/') {  
	    str = str.slice(1);  
	    str = this.leftTrim(str);  
	  }   
	  return str;  
	}, 
	getSuffix(fileName){
		var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
		return fileExtension;
	},
	// 初始化七牛相关参数
	async getQiniuConfig(fileName,suffix){
		var setUploadPath = uni.getStorageSync('setUploadPath'); //设置上传路径
		uni.removeStorageSync('setUploadPath');
		var cacheInfo = uni.getStorageSync(cacheKey);
		//cacheInfo = {};
		var nowTime = parseInt((Date.parse(new Date())) / 1000);
		var qiniuConfigInfo = {
			upToken:'',
			uploadurl:'',
			cdnurl:'',
			savekey:'',
			fileName:'',
		}
		if(cacheInfo.token && cacheInfo.token_exp_time &&  (cacheInfo.token_exp_time - nowTime > 30))
		{
			qiniuConfigInfo = cacheInfo;
		}else{
			apiObj.loadingMsg('获取上传配置');
			var reqUrl = 'config/upload'; ////七牛缓存key
			await http.post(reqUrl,{
				
			}).then(res=>{
				if(res.code == 1)
				{
					uni.setStorageSync(cacheKey,res.data);
					setTimeout(function(){
						uni.removeStorageSync(cacheKey);
						console.log('上传配置已清空')
					},30000)
					qiniuConfigInfo = res.data;
					//upToken = res.data.token;
				}else{
					uni.removeStorageSync(cacheKey);
					apiObj.showModal('七牛配置错误',res.msg,function(){
						
					},{
						hideCancel:true
					})
					/* uni.showToast({
						title:'getQiniuConfig错误：'+res.msg,
						icon:'none'
					}) */
					throw '';
				}
			})
		}
		let  savefileName = qiniuConfigInfo.savekey;
		if(fileName && savefileName)
		{
			let nowDate = new Date();
			let year = nowDate.getFullYear();
			let month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1): nowDate.getMonth() + 1;
			let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
			
			savefileName = savefileName.replace('{year}',year);
			savefileName = savefileName.replace('{mon}',month);
			savefileName = savefileName.replace('{day}',day);
			savefileName = savefileName.replace('{filemd5}',apiObj.getMd5Name(fileName));
			savefileName = savefileName.replace('{.suffix}','.'+suffix);
			if(setUploadPath)
			{
				var uploadPath = 'uniapi/'+setUploadPath+'/'+this.leftTrim(savefileName);
			}else{
				var uploadPath = 'uniapi/'+this.leftTrim(savefileName);
			}
			qiniuConfigInfo.fileName = uploadPath;
		}else{
			qiniuConfigInfo.fileName = '';
		}
		return qiniuConfigInfo;
	},
	async initQiniu(file,suffix) {
		suffix = suffix?suffix:'jpg';
		//console.log(file)
		var qiniuConfigInfo = await this.getQiniuConfig(file,suffix);
		if(!qiniuConfigInfo.fileName)
		{
			return {};
		}
		var options = {
			uploadURL: qiniuConfigInfo.uploadurl, // 华北区
			//uptokenURL: 'https://yourserver.com/api/uptoken',
			uptoken: qiniuConfigInfo.token,
			domain: qiniuConfigInfo.cdnurl,
			key:qiniuConfigInfo.fileName,
		};
		return options;
	},
	encode(str){
		// 对字符串进行编码
		var encode = encodeURI(str);
		// 对编码的字符串转化base64
		var base64 = btoa(encode);
		return base64;
	},
	async uploadImageToQiniuH5Ajax(list,key)
	{
		var that = this;
		var info = list[key];
		if(info)
		{
			var qiniuOptions = await that.initQiniu(info.tempFilePath)
		}
		return new Promise((resolve, reject) =>  {
			if(!info || !qiniuOptions || !qiniuOptions.uploadURL )
			{
				var text = !info?'':'获取上传图片配置出错'
				resolve({
					msg:text,
					list:uploadImgListH5Qiniu
				});
				return ;
			}
			apiObj.loadingMsg('正在上传图片');
			uni.request({
			    url: qiniuOptions.uploadURL+'/putb64/-1/key/'+that.encode(qiniuOptions.key), //仅为示例，并非真实接口地址。
			    data: info.tempFilePath.replace(/^.*?base64,/, ''),
				method:'POST',
			    header: {
			        'Content-Type': 'application/octet-stream',
					'Authorization':'UpToken '+qiniuOptions.uptoken,//自定义请求头信息
			    },
			    success: ( res) => {
					
					if(res.data && res.data.key)
					{
						uploadImgListH5Qiniu.push(qiniuOptions.domain + res.data.key);
						var text = '';
					}else{
						var text = '上传图片失败：'+res.data.error
					}
					if(text)
					{
						resolve({
							msg:text,
							list:uploadImgListH5Qiniu
						});
						return ;
					}
					var keykey = key+1;
					that.uploadImageToQiniuH5Ajax(list,keykey).then(res=>{
						resolve({
							msg:text,
							list:uploadImgListH5Qiniu
						});
					});
			    },
				fail:(res)=>{
					resolve({
						msg:'网络出现错误',
						list:uploadImgListH5Qiniu
					});
					return;
					//console.log(res)
				}
			});
		})
	},
	/**
	 * 上传文件至七牛
	 */
	async uploadImageToQiniuH5(res,allowSize){
		//console.log(res)
		var that = this;
		uploadImageAllowSize = allowSize; //保存允许上传的图片大小
		uploadImgList = [];
		
		return new Promise(async(resolve, reject) =>  {
			uploadImgListH5Qiniu = [];
			if(res.length > 0)
			{
				let compressImgs = [];
				let results = []; 
				res.forEach(function(item,index){
					var path = item.path;
					compressImgs.push(new Promise((resolve, reject) => {
						resolve(path);
						
					}))
					Promise.all(compressImgs) //执行所有需请求的接口
						.then(async(toRes) => {
							if(toRes.length > 0)
							{
								var newRes = [];
								for(var i = 0;i<toRes.length;i++)
								{
									var imageBase64 = uni.getFileSystemManager().readFileSync(toRes[i],'base64')
									//console.log(imageBase64)
									if(!imageBase64)
									{
										continue;
									}
									var tempFilePath = 'data:image/jpeg;base64,'+imageBase64;
									newRes.push({
										tempFilePath:tempFilePath
									}) 
									var jpgSize = that.showSize(tempFilePath);
									if(uploadImageAllowSize > 0 && jpgSize > allowSize)
									{
										//resObj.msg = '请上传小于'+allowSize+'kb的图片';
										resolve({
											msg:'请上传小于'+uploadImageAllowSize+'kb的图片',
											list:[]
										});
										return false;
									}
								}
								//console.log(newRes)
								if(newRes.length > 0)
								{
									await that.uploadImageToQiniuH5Ajax(newRes,0).then( res=>{
										resolve(res)
									}).catch(res=>{
										resolve(res)
									});
								}
							}else{
								resolve([]);
							}
							//console.log(resData.list);
						})
						.catch((res, object) => {
							resolve([]);
						});
				})
			}
		})
	},
	//获取base64图片大小，返回kb数字
	showSize(base64url) {
		//把头部去掉
		var str = base64url.replace('data:image/png;base64,', '');
		var str = str.replace('data:image/jpeg;base64,', '');
		var str = str.replace('data:image/jpg;base64,', '');
		//console.log(str)
		// 找到等号，把等号也去掉
		var equalIndex = str.indexOf('=');
		if(str.indexOf('=')>0) {
			str=str.substring(0, equalIndex);
		}
		// 原来的字符流大小，单位为字节
		var strLength=str.length;
		// 计算后得到的文件流大小，单位为字节
		var fileLength=parseInt(strLength-(strLength/8)*2);
		// 由字节转换为kb
		var size = "";
		size = (fileLength / 1024).toFixed(2);
		var sizeStr = size + ""; //转成字符串
		var index = sizeStr.indexOf("."); //获取小数点处的索引
		var dou = sizeStr.substr(index + 1, 2) //获取小数点后两位的值
		if (dou == "00") { //判断后两位是否为00，如果是则删除00                
			return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
		}
		return size;
	},
	/**
	 * 图片转jpg
	 */
	imageToJpg(file,key){
		var that = this;
		//console.log('uploadImgList',uploadImgList)
		return new Promise((resolve, reject) =>  {
			if(!file[key])
			{
				if(uploadImgList.length <1)
				{
					reject({})
				}else{
					resolve(uploadImgList)
				}
				return ;
			}
			var length = file.length;
			var path = file[key].path;
			uni.getImageInfo({
				src:path,
				success:function(res){
					//console.log(res)
					var ctx = uni.createCanvasContext('firstCanvas')
					var scale = res.width / res.height;//原图宽高比例
					var systemInfo = uni.getSystemInfoSync();
					var windowWidth = systemInfo.windowWidth;
					var windowHeight = systemInfo.windowWidth * 2;
					if(res.width > windowWidth)
					{
						 res.width = windowWidth;
						 res.height = res.width/scale;
					}
					if(res.height > windowHeight)
					{
						res.height = windowHeight
						res.width = res.height*scale;
					}
					if(res.height > 500 || res.width > 500)
					{
						//如果单边尺寸大于500的话，就给他等比例缩小
						res.height = res.height * 0.7;
						res.width = res.width * 0.7;
					}
					ctx.drawImage(path, 0, 0, res.width, res.height)
					ctx.draw(false,function(){
						uni.canvasToTempFilePath({
						  x: 0,
						  y: 0,
						  width: res.width,
						  height: res.height,
						  destWidth: res.width,
						  destHeight: res.height,
						  fileType:'jpg',
						  canvasId: 'firstCanvas',
						  success: function(res) {
							ctx = null;
							var keykey = key+1;
							uploadImgList.push(res)
							that.imageToJpg(file,keykey).then(res=>{
								resolve(uploadImgList);
							}).catch(res=>{
								reject({})
							})
						    // 在H5平台下，tempFilePath 为 base64
						    //resolve(res.tempFilePath);
						  } 
						})
					})
				}
			})
		})
	},
	/**
	 * @param {Object} stringToSearch
	 * @param {Object} arrayToSearch
	 *  获取小数点后两位
	 */
	getParseFloat(number,length){
		length = length?length:2;
		return parseFloat(number).toFixed(length);
	},
	//判断类型是否存在于可允许的类型中
	inArray(stringToSearch, arrayToSearch) {
	     for (var s = 0; s < arrayToSearch.length; s++) {
			var thisEntry = arrayToSearch[s].toString();
			if (thisEntry == stringToSearch) {
			   return true;
			}
	     }
	     return false;
	},
	checkFileType(tempFiles,allowType,allowSize){
		var that = this;
		return new Promise((resolve, reject) => {
			allowSize = allowSize?parseFloat(allowSize):0;
			allowType = allowType?allowType:[];
			var resObj = {
				msg:'',
				list:[]
			};
			if(tempFiles.length > 0)
			{
				
				for(var i=0;i<tempFiles.length;i++)
				{
					//var nowi = i;
					let fileInfo = tempFiles[i];
					// #ifdef H5
					//如果是h5需要判断类型 APP小程序暂时不需要
					let ext = fileInfo.name.slice(fileInfo.name.lastIndexOf(".")+1).toLowerCase();
					if(!ext || ext == '')
					{
						continue;
					}
					if(allowType.length > 0 &&  !this.inArray(ext,allowType))
					{
						//判断类型
						resObj.msg = '请上传正确的'+allowType.join(',')+'格式图片';
						//continue;
					}
					// #endif
					//判断图片大小
					let fileSize = fileInfo.size?this.getParseFloat(fileInfo.size/1024):0;
					if(allowSize > 0 && fileSize > allowSize)
					{
						//resObj.msg = '请上传小于'+allowSize+'kb的图片';
						//continue;
					}
					resObj.list.push({
						path:fileInfo.path,
						size:fileSize,
						name:fileInfo.name?fileInfo.name:'',
						type:fileInfo.type?fileInfo.type:'',
					})
				}
			}else{
				resolve(resObj);  
			}
			if(resObj.list)
			{
				resolve(resObj);
			}
		})
		
	},
	
	chooseImg(params){
		var that = this;
		params = params?params:{};
		let count = (params.count && params.count <=9 && params.count > 0)?params.count:1;
		let sizeType = params.sizeType?params.sizeType:['original', 'compressed'];
		let extension = params.extension?params.extension:[];
		let sourceType = params.sourceType?params.sourceType:['album','camera'];
		var allowType = params.allowType?params.allowType:[];
		var allowSize = params.allowSize?params.allowSize:0;
		return new Promise((resolve, reject) => {
			var initParams = {
			    count: count, //默认9
			    sizeType: sizeType, //可以指定是原图还是压缩图，默认二者都有
			    sourceType: sourceType, //从相册选择
			    success: function (res) {
					//console.log(res.tempFiles)
					var resData = that.checkFileType(res.tempFiles,allowType,allowSize).then(resData=>{
						//console.log(resData)
						if(resData.list.length > 0)
						{
							uploadImageAllowSize = allowSize; //保存允许上传的图片大小
							uploadImgList = [];
							resolve(resData.list)
							
						}else{
							uni.showToast({
								title:'chooseImg错误：'+resData.msg,
								icon:'none'
							})
							resolve([]);
						} 
					}).catch(res=>{
						apiObj.msg('读取图片数据异常');
						resolve([])
					});
					//resolve(res);
			        //console.log(JSON.stringify(res.tempFilePaths));
			    }
			};
			if(extension.length > 0)
			{
				initParams.extension = extension;
			}
			uni.authorize({
				scope:'scope.camera',
				success:function(res){
					// #ifdef MP-TOUTIAO
					uni.authorize({
						scope:'scope.album',
						success:function(res){
							uni.chooseImage(initParams); 
						},
						fail(res) {
							uni.showModal({
								title:'请先允许获取相机和相册权限',
								confirmText:'去授权',
								success:function(res){
									if(res.confirm)
									{
										uni.openSetting({})
									}
								},
							})
						}
					})
					// #endif
					// #ifndef MP-TOUTIAO
					uni.chooseImage(initParams); 
					// #endif
					
				},
				fail(res) {
					uni.showModal({
						title:'请先允许获取相机和相册权限',
						confirmText:'去授权',
						success:function(res){
							if(res.confirm)
							{
								uni.openSetting({})
							}
						},
					})
				}
			})
			
		}).catch(e => {
			reject(e)
		})
	},
	//上传视频
	chooseVideo(params){
		var that = this;
		params = params?params:{};
		let count = (params.count && params.count <=9 && params.count > 0)?params.count:1;
		let compressed = (params.compressed == false)?false:true;
		let extension = params.extension?params.extension:[];
		let sourceType = params.sourceType?params.sourceType:['album','camera'];
		var allowType = params.allowType?params.allowType:[];
		var allowSize = params.allowSize?params.allowSize:0;
		let maxDuration = params.maxDuration?params.maxDuration:60;
		return new Promise((resolve, reject) => {
			var initParams = {
			    count: count, //默认9
			    compressed: compressed, //可以指定是原图还是压缩图，默认二者都有
			    sourceType: sourceType, //从相册选择
				maxDuration:maxDuration,
			    success: function (res) {
					if(res.errMsg == 'chooseVideo:ok')
					{
						if(res.duration > maxDuration)
						{
							apiObj.msg('只能添加'+maxDuration+'秒以内的视频');
							resolve({});
						}
						resolve(res);
					}else{
						apiObj.msg(res.errMsg);
						resolve({});
					}
			    },
				fail:function(res){
					var errMsg = res.errMsg;
					if(errMsg == 'chooseVideo:fail over the max duration')
					{
						errMsg = '只能添加'+maxDuration+'秒内的视频';
						apiObj.msg(errMsg);
					}
					resolve({});
				}
			};
			if(extension.length > 0)
			{
				initParams.extension = extension;
			}
			uni.authorize({
				scope:'scope.camera',
				success:function(){
					// #ifdef MP-TOUTIAO
					uni.authorize({
						scope:'scope.album',
						success:function(res){
							uni.chooseVideo(initParams); 
						},
						fail(res) {
							uni.showModal({
								title:'请先允许获取相机和相册权限',
								confirmText:'去授权',
								success:function(res){
									if(res.confirm)
									{
										uni.openSetting({})
									}
								},
							})
						}
					})
					// #endif
					// #ifndef MP-TOUTIAO
					
					uni.chooseVideo(initParams); 
					// #endif
				},
				fail() {
					uni.showModal({
						title:'请先允许获取相机和相册权限',
						confirmText:'去授权',
						success:function(res){
							if(res.confirm)
							{
								uni.openSetting({})
							}
						},
					})
				}
			})
			
		}).catch(e => {
			reject(e)
		})
	},
	/**
	 * 上传视频至七牛
	 */
	async uploadVideoToQiniu(res){
		var that = this;
		uploadVideoList = [];
		return new Promise(async (resolve, reject) =>  {
			uploadVideoListQiniu = [];
			 await that.uploadVideoToQiniuAjax(res,0).then(res=>{
			 	resolve(res)
			 }).catch(res=>{
			 	resolve(res)
			 });
		})
	},
	async uploadVideoToQiniuAjax(list,key){
		var that = this;
		var info = list[key];
		//console.log(list,key,info)
		if(info)
		{
			var suffix = this.getSuffix(info.tempFile.name)
			if(!suffix || suffix == '')
			{
				info.tempFile.name = '';
			}
			var qiniuOptions = await that.initQiniu(info.tempFile.name,suffix?suffix:'mp4')
		}
		//console.log(qiniuOptions);
		return new Promise(async (resolve, reject) =>  {
			if(!info || !qiniuOptions || !qiniuOptions.uploadURL )
			{
				var text = !info?'':'获取上传视频配置出错'
				resolve({
					msg:text,
					list:uploadVideoListQiniu
				});
				return ;
			}
			var url = qiniuOptions.uploadURL;
			var formData = {
			    'token': qiniuOptions.uptoken,
			    'key': qiniuOptions.key
			};
			apiObj.loadingMsg('正在上传视频');
			uni.uploadFile({
			    url: url,
				//file:info.tempFile,
			    filePath: info.tempFilePath,
			    name: 'file',
			    formData: formData,
			    success: function (res) {
					var dataString = res.data
					var dataObject = JSON.parse(dataString);
					if(dataObject.key)
					{
						uploadVideoListQiniu.push(qiniuOptions.domain + dataObject.key);
						var text = '';
					}else{
						if(dataObject.error == 'file exists')
						{
							//如果是文件已存在
							
							uploadVideoListQiniu.push(formData.key);
							var text = '';
						}else{
							var text = '上传视频失败：'+dataObject.error
						}
					}
					if(!text)
					{
						var keykey = key+1;
						that.uploadVideoToQiniuAjax(list,keykey).then(res=>{
							resolve({
								msg:text,
								list:uploadVideoListQiniu
							});
						});
					}else{
						resolve({
							msg:text,
							list:uploadVideoListQiniu
						});
						return ;
					}
					
			        /* var dataString = res.data
			        var dataObject = JSON.parse(dataString);
			        //do something
			        var imageUrl = config.qiniuImageURLPrefix + dataObject.key;
			        dataObject.imageURL = imageUrl;
			        console.log(dataObject);
			        success(dataObject); */
			    },
			    fail: function (error) {
			        resolve({
			        	msg:error.errMsg?error.errMsg:'网络出现错误',
			        	list:uploadVideoListQiniu
			        });
			        return;
			    }
			})
		})
	},
	//上传文件
	chooseFile(params){
		var that = this;
		params = params?params:{};
		let count = (params.count && params.count <=9 && params.count > 0)?params.count:1;
		let type = params.type?params.type:'';
		let extension = params.extension?params.extension:[];
		return new Promise((resolve, reject) => {
			var initParams = {
			    count: count, //默认9
			    success: function (res) {
					//arr.indexOf('a')
					//getSuffix
					var reslist = [];
					if(res.errMsg == 'chooseFile:ok')
					{
						res.tempFiles.forEach((item,index) =>{
							var suffix = that.getSuffix(item.name);
							if(extension.indexOf('.'+suffix) > -1)
							{
								reslist.push(item);
							}
						})
						resolve(reslist);
					}else{
						resolve({});
					}
			    }
			};
			if(type != '')
			{
				initParams.type = type;
			}
			if(extension.length > 0)
			{
				initParams.extension = extension;
			}
			uni.chooseFile(initParams); 
		}).catch(e => {
			reject(e)
		})
	},
	/**
	 * 上传文件至七牛
	 */
	async uploadFileToQiniu(res,fileObj){
		var that = this;
		uploadFileList = [];
		return new Promise(async (resolve, reject) =>  {
			uploadFileListQiniu = [];
			 await that.uploadFileToQiniuAjax(res,0,'',fileObj).then(res=>{
			 	resolve(res)
			 }).catch(res=>{
			 	resolve(res)
			 });
		})
	},
	async uploadFileToQiniuAjax(list,key,suffix,fileObj){
		var that = this;
		var info = list[key];
		if(info)
		{
			var suffix = this.getSuffix(info.name)
			if(!suffix || suffix == '')
			{
				info.name = '';
			}
			var qiniuOptions = await that.initQiniu(info.name,suffix); 
			//var qiniuOptions = await that.initQiniu(info,'cyxy')
		}
		apiObj.loadingMsg('正在上传文件');
		return new Promise(async (resolve, reject) =>  {
			if(!info || !qiniuOptions || !qiniuOptions.uploadURL )
			{
				var text = !info?'':'获取上传文件配置出错'
				resolve({
					msg:text,
					list:uploadFileListQiniu
				});
				return ;
			}
			var url = qiniuOptions.uploadURL;
			var formData = {
			    'token': qiniuOptions.uptoken,
			    'key': qiniuOptions.key
			};
			console.log(url)
			if(fileObj)
			{
				//console.log(info.fileObj)
				uni.uploadFile({
				    url: url,
					file:info.fileObj,
				    formData: formData,
				    success: function (res) {
						var dataString = res.data
						var dataObject = JSON.parse(dataString);
						if(dataObject.key)
						{
							uploadFileListQiniu.push(qiniuOptions.domain + dataObject.key);
							var text = '';
						}else{
							var text = '上传fileObj文件失败：'+dataObject.error
						}
						if(!text)
						{
							var keykey = key+1;
							that.uploadFileToQiniuAjax(list,keykey).then(res=>{
								resolve({
									msg:text,
									list:uploadFileListQiniu
								});
							});
						}else{
							resolve({
								msg:text,
								list:uploadFileListQiniu
							});
							return ;
						}
				    },
				    fail: function (error) {
				        resolve({
				        	msg:'fileObj'+(error.errMsg?error.errMsg:'网络出现错误'),
				        	list:uploadFileListQiniu
				        });
				        return;
				    }
				})
				
			}else{
				uni.uploadFile({
				    url: url,
				    filePath: info.path,
				    name: 'file',
				    formData: formData,
				    success: function (res) {
						var dataString = res.data
						var dataObject = JSON.parse(dataString);
						if(dataObject.key)
						{
							uploadFileListQiniu.push(qiniuOptions.domain + dataObject.key);
							var text = '';
						}else{
							var text = '上传文件失败：'+dataObject.error
						}
						if(!text)
						{
							var keykey = key+1;
							that.uploadFileToQiniuAjax(list,keykey).then(res=>{
								resolve({
									msg:text,
									list:uploadFileListQiniu
								});
							});
						}else{
							resolve({
								msg:text,
								list:uploadFileListQiniu
							});
							return ;
						}
				    },
				    fail: function (error) {
				        resolve({
				        	msg:error.errMsg?error.errMsg:'网络出现错误',
				        	list:uploadFileListQiniu
				        });
				        return;
				    }
				})
			}
			
		})
	}

	
}
